import {
  createRouter,
  createWebHashHistory,
  createWebHistory
} from "vue-router";
import routes from "./routes";
import { useCachedViewStoreHook } from "@/store/modules/cachedView";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import { createPinia } from "pinia";
import { mainAct } from "@/store/activeda";
import { nextTick } from "vue";
import { menu } from "@/store/menu";
import { generateHash } from "@/utils/hash";

const pinia = createPinia();
let main = null;
nextTick(() => {
  main = mainAct(pinia);
});
const menuStore = menu(pinia);
const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  // main.openLoading();
  console.log("路由前置守卫" + main?.isLoading);

  // 路由缓存
  useCachedViewStoreHook().addCachedView(to);
  // 页面 title
  setPageTitle(to.meta.title);

  next();
});

router.afterEach((to, from, next) => {
  console.log("to, from, next", to.path, from, next);

  NProgress.done();
  if (to.path != "/iframe") {
    const parent = document.getElementsByClassName("scrollable"); // 滚动容器

    if (parent && parent[0] && parent[0].scrollTo) {
      console.log("parent**************", parent);

      parent[0].scrollTo({
        top: 0,
        behavior: "smooth"
      });
    }
  }

  // main.closeLoading();
  console.log("路由后置守卫" + main?.isLoading);
});

export default router;
